import plugins from '../register/plugin.js'
import {gbs} from '../config/index.js'

//阿里云oss
// import OSS from 'ali-oss';/* 安装命令 npm i ali-oss --save */
//需修改配置参数   region  bucket

//七牛云oss
// import * as qiniu from 'qiniu-js';/* 安装命令 npm i qiniu-js --save */

//腾讯oss需要在config中配置参数
//var COS = require('cos-js-sdk-v5');/* 安装命令 npm i cos-js-sdk-v5 --save */

//阿里云点播需要在index。html中引入以下 script
 // <script src="./static/aliyun-oss-sdk-6.13.0.min.js"></script>
 // <script src="./static/aliyun-upload-sdk-1.5.2.min.js"></script>
 // <script src="./static/es6-promise.min.js"></script>


async function file_upload (fileObj,progressBack,finishBack,token) {
  const self = this;
  self.chunkSize = 2 * 1024 * 1024;
  self.finishCount = 0;
  var fileReader = new FileReader();
  fileReader.onload = function(e) { //FileReader的load事件，当文件读取完毕时触发
    self.running = false;
    // e.target指向上面的fileReader实例
    if (fileObj.size != e.target.result.length) { //如果两者不一致说明读取出错
      alert("ERROR:Browser reported success but could not read the file until the end.");
    } else {
      var md5Res = SparkMD5.hashBinary(e.target.result);
      file_main_upload(md5Res,fileObj,progressBack,finishBack,token,self,0);
    }
  };

  fileReader.onerror = function() { //如果读取文件出错，取消读取状态并弹框报错
    self.running = false;
    alert(
      "ERROR:FileReader onerror was triggered, maybe the browser aborted due to high memory usage.");
  };
  self.running = true;
  fileReader.readAsBinaryString(fileObj); //通过fileReader读取文件二进制码
}


async function file_main_upload (md5Res,fileObj,progressBack,finishBack,token,self,start) {


  var obj = fileObj.name.lastIndexOf(".");
  var ext = fileObj.name.substr(obj + 1);
  var orginName = fileObj.name;
  self.totalSize = fileObj.size;
  self.start = start;


  // 上传完成
  if (start >= fileObj.size) {
    return;
  };
  // 获取文件块的终止字节
  self.end = (start + self.chunkSize > fileObj.size) ? fileObj.size : (
    start + self
    .chunkSize);


  // 将文件切块上传

  var param = new FormData() // 创建form对象
  param.append('file', fileObj.slice(start, self.end)) // 通过append向form对象添加数据
  param.append('token', token);
  param.append('md5', md5Res);
  param.append('totalSize', self.totalSize);
  param.append('start', self.start);
  param.append('chunkSize', self.chunkSize);
  param.append('ext', ext);
  param.append('originName', orginName);
  // POST表单数据
  let xhr = new XMLHttpRequest();
  xhr.open('post', gbs.host + 'Base/FtpFile/upload', true);
  xhr.onload = function() {
    if (this.readyState == 4 && this.status == 200) {
      // 上传一块完成后修改进度条信息，然后上传下一块
      var json = JSON.parse(xhr.responseText);

      self.finishCount = json.finishCount;
      if (json.chunk_start) {
        self.file_main_upload (md5Res,fileObj,progressBack,finishBack,token,self,json.chunk_start)
      };
      if (json.solely_code == 100000) {
        console.log('图片路径', json.info.url)
        var url = json.info.url; //获取到了图片的URL
        progressBack(100,self.totalSize)
        finishBack&&finishBack(url,'',self.totalSize)
        

      }
    }
  };

  xhr.upload.onprogress = function(e) {

    var loaded  = e.loaded + self.finishCount * self.chunkSize;
    var complete = (loaded / self.totalSize * 100).toFixed(1);

    if (Math.round(complete) < 100) {
      self.progress = Math.round(complete);
      progressBack&&progressBack(self.progress,loaded);
    };
     

  };

  xhr.send(param);
}









/**
 * 阿里云点播上传
 */
async function ali_db_upload_back (uploadInfo,finishBack) {
  console.log('ali_db_upload_back')
  var res = await plugins['api_getAliPlayInfo']({data: {
    'videoId':uploadInfo.videoId
  }});
  console.log('res',res)
  finishBack&&finishBack(res.PlayInfoList.PlayInfo[0]['PlayURL'],uploadInfo.videoId);
}

async function ali_db_upload (fileObj,progressBack,finishBack,token) {
    var region = 'cn-beijing';

    const self = this;

    const postData = {};
    if(localStorage.getItem("stsTokenDeadtime")&&localStorage.getItem("stsTokenDeadtime")>Date.parse(new Date())){
      var stsToken = localStorage.getItem("stsToken");
      var accessKeyId = localStorage.getItem("accessKeyId");
      var accessKeySecret = localStorage.getItem("accessKeySecret");
    }else{
      var res = await plugins['api_getAliSts']({data: postData});

      if(res.securityToken){
        var stsToken = res.securityToken;
        var accessKeyId = res.accessKeyId;
        var accessKeySecret = res.accessKeySecret;
        localStorage.setItem("stsToken",stsToken);
        localStorage.setItem("accessKeyId",accessKeyId);
        localStorage.setItem("accessKeySecret",accessKeySecret);
        localStorage.setItem("stsTokenDeadtime",new Date(res.expiration).getTime());
      };
    };

    var uploader = new AliyunUpload.Vod({
             //分片大小默认1 MB，不能小于100 KB
           partSize: 1048576,
         userId: 666,//随便输入
         region:region,//储存仓库所在区域
         //并行上传分片个数，默认5
           parallel: 5,
         //网络原因失败时，重新上传次数，默认为3
         retryCount: 3,
         //网络原因失败时，重新上传间隔时间，默认为2秒
         retryDuration: 2,
         //是否上报上传日志到视频点播，默认为true
         enableUploadProgress: true,
          //开始上传
          'onUploadstarted': function (uploadInfo) {
            console.log("onUploadStarted:" + uploadInfo.file.name + ", endpoint:" + uploadInfo.endpoint + ", bucket:" + uploadInfo.bucket + ", object:" + uploadInfo.object);
          //获取STS Token，设置到SDK
             uploader.setSTSToken(uploadInfo, accessKeyId, accessKeySecret, stsToken);
          },
          //文件上传成功
          'onUploadSucceed': async function (uploadInfo) {
            console.log("onUploadSucceed: ",uploadInfo);

            var list = uploader.listFiles();
            console.log("onUploadSucceedList: ",list);
            ali_db_upload_back(uploadInfo,finishBack)
          },
          //文件上传失败
          'onUploadFailed': function (uploadInfo, code, message) {
            console.log("onUploadFailed: file:" + uploadInfo.file.name + ",code:" + code + ", message:" + message);
          },
          //文件上传进度，单位：字节
          'onUploadProgress': function (uploadInfo, totalSize, loadedPercent) {
             progressBack&&progressBack(Math.ceil(loadedPercent * 100));
              console.log("onUploadProgress:file:" + uploadInfo.file.name + ", fileSize:" + totalSize + ", percent:" + Math.ceil(loadedPercent * 100) + "%");
          },
          //STS token超时
          'onUploadTokenExpired': function (uploadInfo) {
              console.log("onUploadTokenExpired");
              //重新获取STS token，恢复上传
          uploader.resumeUploadWithSTSToken(accessKeyId, accessKeySecret, stsToken);
          },
        //全部文件上传结束
        'onUploadEnd':function(uploadInfo){
               console.log("onUploadEnd: uploaded all the files");
           }
      });



    var paramData = '{"Vod":{"Title":"solely","CateId":"1"}}';

    uploader.addFile(fileObj, null, null, null, paramData);
    uploader.startUpload();
};




//阿里OSS上传
async function ali_oss_upload (fileObj,progressBack,finishBack,token) {
  //配置参数
    var region = 'oss-cn-beijing';
    var bucket = 'solely-test-one';
    var backUrl = 'http://'+bucket+'.'+region+'.aliyuncs.com/';

    const self = this;
    const postData = {};
    if(localStorage.getItem("aliStsDeadtime")&&localStorage.getItem("aliStsDeadtime")>Date.parse(new Date())){
      var aliSts = localStorage.getItem("aliSts");
    }else{
      var res = await plugins['api_getAliSts']({data: postData});
      if(res.securityToken){
        var aliSts = {
          'stsToken':res.securityToken,
          'accessKeyId':res.accessKeyId,
          'accessKeySecret':res.accessKeySecret,
        };
        localStorage.setItem("aliSts",aliSts);
        localStorage.setItem("aliStsDeadtime",new Date(res.expiration).getTime()-3600000);
      };
    };
    var stsToken = aliSts.securityToken;
    var accessKeyId = aliSts.accessKeyId;
    var accessKeySecret = aliSts.accessKeySecret;


    self.size  = fileObj.size;
    var key = 'solely/'+new Date().getTime()+fileObj.name;
    var obj = fileObj.name.lastIndexOf(".");
    self.ext = fileObj.name.substr(obj+1);
    self.orginName = fileObj.name;
    self.start_time = new Date().getTime();
    let client = new OSS({
      region: region,
      //阿里云账号AccessKey拥有所有API的访问权限，建议遵循阿里云安全最佳实践，创建并使用STS方式访问API。
      accessKeyId:accessKeyId,
      accessKeySecret:accessKeySecret,
      stsToken: stsToken,
      bucket:bucket
    });

    const progress = function progress(p, checkpoint) {
      console.log('p',p);
      progressBack&&progressBack(p*100)
    };
    try {
      // object表示上传到OSS的文件名称。
      // file表示浏览器中需要上传的文件，支持HTML5 file和Blob类型。
      let result = await client.multipartUpload(key, fileObj,{progress: progress});
      finishBack&&finishBack(backUrl+result.name,'',self.size)

    } catch (e) {
      console.error('error: %j', e);
    }

};


async function qiniu_oss_upload (fileObj,progressBack,finishBack,token) {
    const self = this;

    const postData = {
      'token':token,
      'config_id':2
    };
    //ACCESSKEY->app_id;SECRETKEY->app_secret;backUrl->绑定域名；bucket->bucket
    var res = await plugins['api_getQiniuSts']({data: postData});
    if(res.info.token){
      var stsToken = res.info.token;
      var backUrl = res.info.backUrl;
    };

    console.log('stsToken',stsToken)

    self.size  = fileObj.size;
    var key = 'solely/'+new Date().getTime()+fileObj.name;
    var obj = fileObj.name.lastIndexOf(".");
    self.ext = fileObj.name.substr(obj+1);
    self.orginName = fileObj.name;
    self.start_time = new Date().getTime();

    let config = {
       useCdnDomain: false,   //表示是否使用 cdn 加速域名，为布尔值，true 表示使用，默认为 false。
       region: null     // 根据具体提示修改上传地区,当为 null 或 undefined 时，自动分析上传域名区域
     };
     let putExtra = {
       fname: "",  //文件原文件名
       params: {}, //用来放置自定义变量
       mimeType: null  //用来限制上传文件类型，为 null 时表示不对文件类型限制；限制类型放到数组里： ["image/png", "image/jpeg", "image/gif"]
     };


     var observable = qiniu.upload(fileObj, key, stsToken, putExtra, config);
     observable.subscribe({
       next: (result) => {
       // 主要用来展示进度
         console.log('progressBack',result);
        progressBack&&progressBack(result.total.percent)
       },
       error: (errResult) => {
       // 失败报错信息
         console.log(errResult)
       },
       complete: (result) => {
       // 接收成功后返回的信息
         finishBack&&finishBack(backUrl+result.key);

       }
     });

};



async function tencent_oss_upload (fileObj,progressBack,finishBack,token) {
    const self = this;

   var cos = new COS({
      SecretId: gbs.tecncent_oss.SecretId,
      SecretKey: gbs.tecncent_oss.SecretKey,
   });


   self.size  = fileObj.size;
   var key = 'solely/'+new Date().getTime()+fileObj.name;
   var obj = fileObj.name.lastIndexOf(".");
   self.ext = fileObj.name.substr(obj+1);
   self.orginName = fileObj.name;
   self.start_time = new Date().getTime();

   cos.putObject({
      Bucket:gbs.tecncent_oss.Bucket, /* 必须 */
      Region: gbs.tecncent_oss.Region,     /* 存储桶所在地域，必须字段 */
      Key: key,              /* 必须 */
      StorageClass: 'STANDARD',
      Body: fileObj, // 上传文件对象
      onProgress: function(progressData) {
        var progressRes = progressData;
        console.log('progressRes',progressRes)
        progressBack&&progressBack(progressRes.percent*100)
      }
   }, function(err, data) {
      finishBack&&finishBack('http://'+data.Location);
   });

};


export default {
  ali_db_upload,
  file_upload,
  file_main_upload,
  ali_oss_upload,
  qiniu_oss_upload,
  tencent_oss_upload

}
